package com.ciwong.epaper.util;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.webkit.MimeTypeMap;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.service.UploadServiceHelper;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.utils.ZipHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.ciwong.epaper.service.UploadServiceHelper.FILE_FLAGE_UPLOADED_ANSWER_CIONG;

/**
 * 获取文件返回KEY（lib工程反射调用方法）
 *
 * @author bin
 * @version ciwong v.1.0 2015/9/8 16:07
 * @since ciwong v.1.0
 */
public class FileUtil {

    /**
     * 通知字节长度获取文件大小
     *
     * @param length 字节
     * @return 文件大小
     */
    public static String getFileLength(long length) {
        final float thousandTweetyFor = 1024.0f;
        final int two = 2;
        final int three = 3;
        final int four = 4;
        final int five = 5;
        DecimalFormat df = new DecimalFormat("#.00");
        if (length < thousandTweetyFor) {
            return String.valueOf(length) + "B";
        } else if (length >= thousandTweetyFor
                && length < Math.pow(thousandTweetyFor, two)) {
            return String.valueOf(df.format(length / thousandTweetyFor)) + "KB";
        } else if (length >= Math.pow(thousandTweetyFor, two)
                && length < Math.pow(thousandTweetyFor, three)) {
            return String
                    .valueOf(df
                            .format(length / Math.pow(thousandTweetyFor, two)))
                    + "MB";
        } else if (length >= Math.pow(thousandTweetyFor, three)
                && length < Math.pow(thousandTweetyFor, four)) {
            return String
                    .valueOf(df.format(
                            length / Math.pow(thousandTweetyFor, three)))
                    + "GB";
        } else if (length >= Math.pow(thousandTweetyFor, four)
                && length < Math.pow(thousandTweetyFor, five)) {
            return String
                    .valueOf(df
                            .format(length / Math.pow(thousandTweetyFor, four)))
                    + "TB";
        } else {
            return "";
        }
    }

    /**
     * 是否有SD卡
     *
     * @return
     */
    public static boolean haveSDCard() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 拷贝asset目录下文件到sd卡上
     *
     * @param srcfilename 文件名
     * @param file        文件路径
     * @return 复制文件
     */
    public static boolean copyFile(Context context, String srcfilename, File file) {
        FileOutputStream fos = null;
        try {
            final int bufferSize = 1024;
            AssetManager am = context.getResources().getAssets();
            InputStream is = am.open(srcfilename);
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[bufferSize];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static String getShareIconLocalPath(Context context) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "lsw_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(context, "lsw_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String getShareWordIconLocalPath(Context context) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "word_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(context, "word_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String getShareAppIconLocalPath(Context context) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "share_ic_launcher.jpg";
        File targetFile = new File(targetPath);
        try {
            if (targetFile.exists()) {
                targetFile.delete();
            }
        } catch (Exception e) {

        }

        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(context, "share_ic_launcher.jpg", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }


    public static void CheckEpaperHtmlExists() {
        String targetPath = ESystem.getProjectFolderPath()
                + File.separator + ESystem.ONLINE_PAPER + ".zip";
        File targetFile = new File(targetPath);
        String onLinePaperHtmlPath = ESystem.getProjectFolderPath()
                + File.separator + ESystem.ONLINE_PAPER + File.separator + "paper.html";
        File onLinePaperHtmlFile = new File(onLinePaperHtmlPath);
        if (!onLinePaperHtmlFile.exists()) {
            FileUtil.copyFile(EApplication.getInstance(), ESystem.ONLINE_PAPER + ".zip", targetFile);
            ZipHelper.getInstance().addToUpZipTask(
                    targetPath, ESystem.getProjectFolderPath());
        }
    }


    /**
     * 删除空目录
     *
     * @param dir 将要删除的目录路径
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.exists() && dir.isDirectory()) {
            String[] children = dir.list();
            if (children != null) {
                //递归删除目录中的子目录下
                for (int i = 0; i < children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }


    public static String getShareOnlineAnswerIconLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "onlineanswer_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(applicationContext, "onlineanswer_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String getShareRankIconLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "rank_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(applicationContext, "rank_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String getSharePKIconLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "pk_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(applicationContext, "pk_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String makeShareReciteWordIconLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "recite_word_share_icon.png";
//        File targetFile = new File(targetPath);
        return targetPath;
    }

    public static String getShareReciteWordIconLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "recite_word_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(applicationContext, "recite_word_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    public static String makeShareIntegralDialogLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "integral_dialog_share_icon.png";
        return targetPath;
    }

    public static String getShareIntegralDialogLocalPath(Context applicationContext) {

        String targetPath = ESystem.getShareIconPath() + File.separator + "integral_dialog_share_icon.png";
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
                boolean isSuccess = FileUtil.copyFile(applicationContext, "integral_dialog_share_icon.png", targetFile);
                if (isSuccess) {
                    return targetPath;
                } else {
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return targetPath;
    }

    /**
     * 压缩图片
     *
     * @param inputFilePath
     * @param outputFilePath
     * @param quality        1-100,越小代表压缩的比例越高。
     * @return 压缩图片，处理某些手机拍照角度旋转的问题
     * @throws FileNotFoundException
     */
    public static String compressImage(String inputFilePath, String outputFilePath, int quality) throws Exception {

        Bitmap smallBitmap = getSmallBitmap(inputFilePath);

        int degree = readPictureDegree(inputFilePath);

        if (degree != 0) {//旋转照片角度
            smallBitmap = rotateBitmap(smallBitmap, degree);
        }
        File outputFile = new File(outputFilePath);

        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);

        smallBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);

        return outputFile.getPath();
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 700, 1000);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    //计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

    /**
     * 递归查找文件夹
     *
     * @param baseDirName   查找的文件夹路径
     * @param targetDirName 需要查找的文件夹名
     */
    public static List<String> findDirs(String baseDirName, String targetDirName) {

        List<String> dirs = new ArrayList<>();
        File baseDir = new File(baseDirName);        // 创建一个File对象
        if (!baseDir.exists() || !baseDir.isDirectory()) {    // 判断目录是否存在
            System.out.println("文件查找失败：" + baseDirName + "不是一个目录！");
            return dirs;
        }
        //判断目录是否存在
        File tempFile;
        File[] files = baseDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            tempFile = files[i];
            if (tempFile.isDirectory()) {
                if (tempFile.getName().contains(targetDirName)) {
                    dirs.add(tempFile.getAbsolutePath());
                }
            }
        }
        return dirs;
    }

    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param fileName 要删除的文件名
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * 删除空文件夹仅用于“answer”文件
     *
     * @param flagUploadedHomework 上传过作业的标记
     * @param fileName             要删除的空文件夹的路径
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteOnlyContainUploadedFlag(String fileName, String flagUploadedHomework) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return false;//当文件不存在或是文件不是文件夹

        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list == null || list.length <= 0) return false;
            if (list.length == 1 && list[0].getAbsolutePath().contains(flagUploadedHomework)) {//当文件是文件夹并且文件内为空
                System.out.println("lzh==>> 有空文件夹");
                return list[0].delete() && file.delete();
            } else {
                boolean flag = false;
                for (File fileInner : list) {
                    if (deleteOnlyContainUploadedFlag(fileInner.getAbsolutePath(), flagUploadedHomework))
                        flag = true;
                }
                return flag;
            }
        } else {
            return false;
        }
    }

    /**
     * 删除空文件夹仅用于“answer”文件
     *
     * @param fileName 要删除的空文件夹的路径
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteEmptyDir(String fileName) {
        boolean flag = false;
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return false;//当文件不存在或是文件不是文件夹
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list == null) return false;
            if (list.length <= 0) {//当文件是文件夹并且文件内为空
                System.out.println("lzh==>> 有空文件夹");
                return file.delete();
            } else {
                for (int i = 0; i < list.length; i++) {
                    if (deleteEmptyDir(list[i].getAbsolutePath()))
                        flag = true;
                }
                if (file.list() == null) return flag;
                if (file.list().length <= 0) {//确保外层“answer'文件不被删除
                    if (file.delete()) flag = true;
                }
                return flag;
            }
        } else {
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else if (files[i].isDirectory()) {// 删除子目录
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 遍历文件夹查询所有MP3文件
     *
     * @param dir
     * @return
     */
    public static List<String> findMp3s(String dir) {
        List<String> listReturn = new ArrayList<>();
        File file = new File(dir);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return listReturn;//当文件不存在或是文件不是文件夹
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles == null || listFiles.length <= 0) return listReturn;
            for (int i = 0; i < listFiles.length; i++) {
                listReturn.addAll(findMp3s(listFiles[i].getAbsolutePath()));
            }
        } else {
            String absolutePath = file.getAbsolutePath();
            if (absolutePath != null && absolutePath.endsWith(".mp3"))
                listReturn.add(absolutePath);
        }
        return listReturn;
    }

    /**
     * 查找重命名后的文件
     *
     * @param dir
     * @param specialCharDir 单词作业 文件夹标记 {@linkUploadServiceHelper.FILE_FLAGE_UPLOADED_DIR}
     * @return
     */
    public static List<String> findMp3DirContainedSpecialChar(String dir, String specialCharDir) {
        List<String> listReturn = new ArrayList<>();
        File file = new File(dir);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return listReturn;//当文件不存在或是文件不是文件夹
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles == null || listFiles.length <= 0) return listReturn;
            for (int i = 0; i < listFiles.length; i++) {
                File listFile = listFiles[i];
                String absolutePath = listFile.getAbsolutePath();
                if (absolutePath.contains(specialCharDir)) {
                    listReturn.add(absolutePath);
                } else {//不包含特殊字符（即是未重命名）
                    String[] listInner = listFile.list();
                    boolean flagUploadHomework = false;
                    if (listInner != null && listInner.length > 0) {
                        for (String str : listInner) {
                            if (str.contains(FILE_FLAGE_UPLOADED_ANSWER_CIONG)) {
                                listReturn.add(absolutePath);
                                flagUploadHomework = true;
                                break;
                            }
                        }
                    }
                    if (!flagUploadHomework)//当这个文件夹中没有提交过作业的标记文件
                        listReturn.addAll(findMp3DirContainedSpecialChar(absolutePath, specialCharDir));
                }
            }
        }
        return listReturn;
    }

    /**
     * 查找给定文件夹中所有未上传成功的文件（上传成功的文件有标记）
     *
     * @param dir
     * @param specialCharFile MP3文件的标记哦 {@linkUploadServiceHelper.FILE_FLAGE_UPLOADED_FILE}
     * @return
     */
    public static List<String> findMp3FileContainedSpecialChar(String dir, String specialCharFile) {
        List<String> listReturn = new ArrayList<>();
        File file = new File(dir);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return listReturn;//当文件不存在或是文件不是文件夹
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles == null || listFiles.length <= 0) return listReturn;
            for (int i = 0; i < listFiles.length; i++) {
                File listFile = listFiles[i];
                String absolutePath = listFile.getAbsolutePath();
                if (listFile.isDirectory()) {//是文件夹的情况下
                    listReturn.addAll(findMp3FileContainedSpecialChar(absolutePath, specialCharFile));
                } else {//是文件 不是文件夹的情况下
                    //mp3 文件 并且是不包含上传成功标记的
                    if (absolutePath != null && absolutePath.endsWith(".mp3") && !absolutePath.contains(specialCharFile)) {
                        listReturn.add(absolutePath);
                    }
                }
            }
        } else {
            String absolutePath = file.getAbsolutePath();
            //mp3 文件 并且是不包含上传成功标记的
            if (absolutePath != null && absolutePath.endsWith(".mp3") && !absolutePath.contains(specialCharFile)) {
                listReturn.add(absolutePath);
            }

        }
        return listReturn;
    }


    /**
     * 音频文件作业的文件夹
     *
     * @param dir  音频所在文件夹
     * @param flag 提交玩作业的标记
     * @return
     */
    public static boolean makeFlagUploadedHomework(String dir, String flag) {
        boolean flagMake = false;
        File file = new File(dir);
        if (!file.exists())
            file.mkdirs();

        File fileFlag = new File(file, flag);
        if (!fileFlag.exists()) {
            try {
                if (fileFlag.createNewFile()) {
                    flagMake = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
                flagMake = false;
            }
        }
        return flagMake;
    }

    public static String getReNameDirPath(String tarPath) {
        if (tarPath.contains(UploadServiceHelper.FILE_FLAGE_UPLOADED_DIR))
            return tarPath;//当重命名之后，不再重命名（包含uploadeddir_则为重命名过）
        String parePath = tarPath.substring(0, tarPath.lastIndexOf(File.separator) + 1);
        String reNamePath = tarPath.replace(parePath, parePath + UploadServiceHelper.FILE_FLAGE_UPLOADED_DIR);
        return reNamePath;
    }

    public static boolean reNameDir(String orgPath, String reNamePath) throws Exception {
        boolean renamed = false;
        File orgFile = new File(orgPath);
        File newFile = new File(reNamePath);
        if (!newFile.exists()) {
            try {
                newFile.mkdirs();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("lzh==>!newFile :" + newFile);
        }
        if (orgFile.exists()) {
            renamed = orgFile.renameTo(newFile);
            System.out.println("lzh==>renameTodir :" + renamed);
            if (!renamed) {
                throw new Exception("rename failed!");
            } else {
                boolean delete = orgFile.delete();
                System.out.println("lzh==>rename delete :" + delete);
            }
        }
        return renamed;
    }

    public static String reNameFile(String orgPath) {
        if (orgPath.contains(UploadServiceHelper.FILE_FLAGE_UPLOADED_FILE)) return orgPath;
        String renamedPath = "";
        try {
            File orgFile = new File(orgPath);
            String newFilePath = getReNameFilePath(orgPath);
            File newFile = new File(newFilePath);
            if (!newFile.exists()) {
                try {
                    newFile.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("lzh==>!newFile :" + newFile);
            }
            if (orgFile.exists()) {
                boolean renameed = orgFile.renameTo(newFile);
                if (renameed)
                    renamedPath = newFilePath;
                System.out.println("lzh==>renameTofile :" + renameed);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return renamedPath;
    }

    public static String getReNameFilePath(String tarPath) {
        if (tarPath.contains(UploadServiceHelper.FILE_FLAGE_UPLOADED_FILE)) return tarPath;
        String newFilePath = tarPath.substring(0, tarPath.lastIndexOf(File.separator) + 1) + UploadServiceHelper.FILE_FLAGE_UPLOADED_FILE + tarPath.substring(tarPath.lastIndexOf(File.separator) + 1);
        return newFilePath;
    }

    public static void renameDirContainUploadedFlag(String fileName, String flagUploadedHomework) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (!file.exists()) return;//当文件不存在或是文件不是文件夹
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            if (list == null || (list.length <= 0)) return;
            for (File fileHomework : list) {
//                if ( fileHomework.list().length <=0)
                String absolutePath = fileHomework.getAbsolutePath();
                if (fileHomework.isDirectory()) {
                    //是文件夹并且重命名过
                    if (fileHomework.getAbsolutePath().contains(UploadServiceHelper.FILE_FLAGE_UPLOADED_DIR)) {
                        continue;//进行下一轮循环
                    } else {
                        renameDirContainUploadedFlag(fileHomework.getAbsolutePath(), flagUploadedHomework);
                    }
                } else {
                    //是文件 并且路径没有重命名过
                    if (absolutePath.contains(flagUploadedHomework)
                            && !absolutePath.contains(UploadServiceHelper.FILE_FLAGE_UPLOADED_DIR)) {
                        try {
                            reNameDir(file.getAbsolutePath(), getReNameDirPath(file.getAbsolutePath()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }

                }
            }
        }
    }

    public static File uriToFileApiQ(Uri uri, Context context) {
        File file = null;
        if (uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

//            注释掉的方法可以获取到原文件的文件名，但是比较耗时
//            Cursor cursor = contentResolver.query(uri, null, null, null, null);
//            if (cursor.moveToFirst()) {
//                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));}

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath(), displayName);
//                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, cache, true);
                file = cache;
//                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }


}
